package com.android.baseconfig.data.http.retrofit2.converter;

import android.text.TextUtils;

import com.android.baseconfig.base.BaseApiResult;
import com.android.baseconfig.data.http.retrofit2.exception.ApiException;
import com.android.baseconfig.data.http.retrofit2.exception.HttpErrorCode;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private Type apiResultObjectType;

    JsonResponseBodyConverter() {
    }

    public JsonResponseBodyConverter(Type apiResultObjectType) {
        this.apiResultObjectType = apiResultObjectType;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        if (apiResultObjectType != null) {
            String json = value.string();
            if (!TextUtils.isEmpty(json)) {
                try {
                    return (T) parseApiResult(json);
                } catch (JSONException e) {
                    //e.printStackTrace();
                    //既然出现解析错误，给上层返回后台到底返回的是什么，导致解析失败，这样才能进一步快速分析问题
                    ApiException apiException = new ApiException(HttpErrorCode.PARSE_ERROR, e.getMessage());
                    apiException.setDisplayMessage( e.getMessage()+ ":" + json);
                    throw apiException;
                }
            }
        }
        return (T) value.string();
    }

    private BaseApiResult parseApiResult(String json) throws JSONException {
        if (TextUtils.isEmpty(json)) {
            return null;
        }
        JSONObject jsonObject = new JSONObject(json);
        BaseApiResult<Object> apiResult = new BaseApiResult<Object>();
        if (jsonObject.has("status")) {
            apiResult.status = (jsonObject.getInt("status"));
        }
        if (jsonObject.has("data")) {
            apiResult.data =  (jsonObject.getString("data"));
        }
        if (jsonObject.has("message")) {
            apiResult.message = (jsonObject.getString("message"));
        }
        return apiResult;
    }
}